package com.sgb.kjwl.view.widget;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.sgb.capital.view.widget.MToast;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.databinding.PopwindowMapCarBinding;
import com.sgb.kjwl.model.entity.transport.MapCarEntity;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.LogisticsPermissionHelper;
import com.sgb.kjwl.utils.NumberUtil;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.util.PermissionCheckUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.utils.VehicleConstant;
import com.sgb.kjwl.view.ui.activity.self.logistics.InquiryActivity;
import com.sgb.kjwl.view.ui.activity.transport.CarriageDetailActivity;
import com.sgb.kjwl.view.ui.activity.transport.InquireByLetterActvity;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.PopViewHolder;
import com.swgk.core.dialog.RoundDialog;

import java.math.BigDecimal;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: 杨畔
 * @date: 2021/9/13 14:58
 * @Description: 竞价承运marker弹窗
 */
public class MapCarPopWindow extends BasePopWindow<Object> implements View.OnClickListener {
    private PopwindowMapCarBinding binding;
    private MapCarEntity mEntity;
    protected OnClickCallBack onClickCallBack;

    public void setOnClickCallBack(OnClickCallBack onClickCallBack) {
        this.onClickCallBack = onClickCallBack;
    }

    public interface OnClickCallBack {
        void message(String account);
    }

    public MapCarPopWindow(Context context) {
        super(context, DIR_DOWN_UP);
    }

    @Override
    protected int popLayout() {
        return R.layout.popwindow_map_car;
    }

    @Override
    protected void initView(PopViewHolder holder) {
        binding = (PopwindowMapCarBinding) holder.getmBinding();
        binding.tvMsg.setOnClickListener(this);
        binding.tvTel.setOnClickListener(this);
        binding.tvInquireByLetter.setOnClickListener(this);
        binding.tvInvite.setOnClickListener(this);
        binding.tvBtn.setOnClickListener(this);
        binding.infoLayout.setOnClickListener(this);
    }

    /**
     * 设置数据
     */
    public void setData(MapCarEntity entity) {
        mEntity = entity;
        if (mEntity == null) return;
        binding.tvNumber.setText(String.format("%s", entity.getCarNumber()));
        binding.tvDriver.setText(String.format("%s", entity.getName()));
        if (BigDecimal.ZERO.compareTo(BigDecimal.valueOf(entity.getDistance())) != 0) {
            binding.tvDistance.setText(String.format("%s", entity.getDistance() < 1000
                    ? "距您1km以内"
                    : String.format("%skm", "距您" + NumberUtil.trim0(entity.getDistance() / 1000))));
        }
        binding.tvCarInfo.setText(String.format("%s %s %s吨%s%s",
                entity.getCarTypeName(),
                entity.getCarLenName(),
                NumberUtil.trim0(entity.getWeight()),
                TextUtils.isEmpty(entity.getHeightHurdle())
                        ? ""
                        : String.format(" %s米", entity.getHeightHurdle()),
                entity.getIsDump() == null
                        ? ""
                        : String.format(" %s", VehicleConstant.getIsDumpStr(entity.getIsDump()))));
        binding.tvIntentionally.setText(String.format("意向地：%s  %s",
                DefaultUtil.getString(entity.getDestCityName()),
                DefaultUtil.getString(entity.getDestDistrictName())));
        binding.tvPriceTip.setText("意向运费：");
        binding.tvPrice.setText(String.format("%s", entity.getFreight() == 0
                ? ""
                : String.format("%s%s", NumberUtil.trim0(entity.getFreight()), entity.getFreightUnit())));

        if (entity.getDiscuss() != null && entity.getDiscuss() == 1) {
            binding.tvPrice.setText("商议");
        } else {
            String kms = "";
            if (entity.getKilometre() != null && entity.getKilometre() > 0) {
                kms = NumberUtil.trim0(entity.getKilometre()) + "公里内";
            }
            binding.tvPrice.setText(kms + NumberUtil.trim0(entity.getFreight()) + entity.getFreightUnit());
        }

        if (!TextUtils.isEmpty(entity.getRoleName())) {
            binding.issuerName.setText(entity.getRoleName());
        }
        if (entity.getTerminal() != null) {
            int resId = R.drawable.geren_person_touxiang;
            switch (entity.getTerminal()) {
                case 1:
                    resId = R.mipmap.icon_company_default;
                    break;
                case 2:
                    resId = R.mipmap.icon_team_default_1;
                    break;
                case 3:
                    resId = R.drawable.geren_person_touxiang;
                    break;
            }

            if (!TextUtils.isEmpty(entity.getImg()))
                Glide.with(mContext)
                        .load(entity.getImg())
                        .placeholder(resId)
                        .error(resId)
                        .into(binding.issuerImg);
            else
                binding.issuerImg.setImageResource(resId);
        }

        //无im信息置灰消息按钮
        if (entity.getUserVo() == null || TextUtils.isEmpty(entity.getUserVo().getImAccount())) {
            binding.tvMsg.setAlpha(0.5f);
            binding.tvMsg.setEnabled(false);
        } else {
            binding.tvMsg.setAlpha(1f);
            binding.tvMsg.setEnabled(true);
        }
        //无手机号信息置灰联系按钮
        if (TextUtils.isEmpty(entity.getTelephone())) {
            binding.tvTel.setAlpha(0.5f);
            binding.tvTel.setEnabled(false);
        } else {
            binding.tvTel.setAlpha(1f);
            binding.tvTel.setEnabled(true);
        }
        resetImMsg(entity);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_msg:
                imClick();
                break;
            case R.id.tv_tel:
                telClick();
                break;
            case R.id.tv_invite:
                //邀请
                LogisticsPermissionHelper.getInstance().checkPermissionToInvite(mContext, "", 0);
                break;
            case R.id.tv_inquire_by_letter:
                inquireByLetter();
                break;
            case R.id.tv_btn:
                inquiryClick();
                break;
            case R.id.info_layout:
                infoLayoutClick();
                break;
        }
    }

    private void infoLayoutClick() {
        CarriageDetailActivity.start(mContext, mEntity.getCarrierNo(), 1);
    }

    private void imClick() {
        //检查登录状态
        if (UserOperating.getInstance().isNotLogged(mContext)) {
            return;
        }
        if (mEntity != null && mEntity.getUserVo() != null) {
            if (onClickCallBack != null) {
                onClickCallBack.message(mEntity.getUserVo().getImAccount());
            }
            //清除消息提醒
//            if (onResultCallBack != null) {
//                onResultCallBack.result(mEntity.getImContact());
//            }
            resetImMsg(mEntity);
        }
    }

    private void telClick() {
        //检查登录状态
        if (UserOperating.getInstance().isNotLogged(mContext)) {
            return;
        }
        if (mEntity != null && !TextUtils.isEmpty(mEntity.getTelephone())) {
            showTelDialog(mEntity.getTelephone());
        }
    }

    private void inquireByLetter() {
        //函询
        if (UserOperating.getInstance().isNotLogged(mContext)) {
            return;
        }
        InquireByLetterActvity.start(mContext, 3,
                mEntity.getName(), mEntity.getUserNo(), mEntity.getCarrierNo(),
                String.format("%s %s->%s %s",
                        mEntity.getShipCityName(),
                        mEntity.getShipDistrictName(),
                        mEntity.getDestCityName(),
                        mEntity.getDestDistrictName())
        );
    }

    private void inquiryClick() {
        if (UserOperating.getInstance().isNotOpenFundAccount(mContext, PermissionCheckUtil.KEY_WODEXUNJIA)) {
            return;
        }
        NewAPIManager.getInstance().getLogisticsAPI().getInquiryPermissions("", mEntity.getCarrierNo()).enqueue(new ICallBack<BaseEntity<Boolean>>() {
            @Override
            public void onSuccess(BaseEntity<Boolean> data) {
                if(data.isSuccess()){
                    if (data.getData()) {
                        if (mEntity != null) {
                            //询价填写资料页
                            InquiryActivity.startCarriageInquiry(mContext, DefaultUtil.getString(mEntity.getCarrierNo()), mEntity.getTelephone());
                            //清除消息提醒
                            if (onResultCallBack != null) {
                                onResultCallBack.result(mEntity.getImContact());
                            }
                        }
                    } else {
                        MToast.showToast(mContext, "不能对自己发布的承运进行询价！");
                    }
                }
            }
        });
    }

    /**
     * 设置im消息红点
     */
    private void resetImMsg(MapCarEntity entity) {
//        if (entity.getImContact() != null && entity.getImContact().getUnreadCount() > 0) {
//            binding.tvMsgBadge.setText(entity.getImContact().getUnreadCount() > 99
//                    ? "99+"
//                    : String.valueOf(entity.getImContact().getUnreadCount()));
//            binding.tvMsgBadge.setVisibility(View.VISIBLE);
//        } else {
        binding.tvMsgBadge.setVisibility(View.GONE);
//        }
    }

    private void showTelDialog(String phone) {
        new RoundDialog.Builder(mContext)
                .title("是否拨打电话")
                .content(phone)
                .confirm("拨打")
                .cancelable(false)
                .confirmCallback(v -> {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    mContext.startActivity(intent);
                })
                .show();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        clearAlpha();
    }
}
